package com.qiu.greened.ui.post

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.qiu.greened.bean.PostBean
import com.qiu.greened.bean.UserBean
import com.qiu.greened.data.PostUserPagingSource
import com.qiu.greened.network.PostService
import com.qiu.greened.network.ServiceCreator
import com.qiu.greened.network.UserService
import com.qiu.greened.utils.MyData
import com.qiu.greened.utils.showToast
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch

class PostUserViewModel : ViewModel() {

    private val postService by lazy {
        ServiceCreator.create<PostService>()
    }

    private val _user = MutableLiveData<UserBean>().apply {

    }
    val user: LiveData<UserBean> = _user

    fun loadUser(userId: Int) {
        viewModelScope.launch {
            try {
                val data = ServiceCreator.create<UserService>()
                    .getUserInfo(MyData.token, userId, MyData.userId).dataConvert()
                _user.value = data
            } catch (e: Exception) {
                e.printStackTrace()
                "${e.message}".showToast()
                Log.i("请求失败", "${e.message}")
            }
        }
    }

    /**
     * cachedIn() 将服务器返回的数据在 viewModelScope 这个作用域内进行缓存
     */
    fun getPagingData(userId: Int): Flow<PagingData<PostBean>> {
        return Pager(PagingConfig(pageSize = 10)) {
            PostUserPagingSource(postService, userId)
        }.flow.cachedIn(viewModelScope)
    }
}